package downloadfiletask

import (
	"cvevulner/cve-timed-task/util"
	"fmt"
	"github.com/antchfx/htmlquery"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"io"
	"net/http"
	"os"
	"strings"
)

func HandleOne() (string, error) {
	filePath := beego.AppConfig.String("timedtask::packageDir") + "newexcels/"
	dErr := util.MakeDir(filePath)
	if dErr != nil {
		logs.Error("util.makeDir error: ", dErr)
		return "", dErr
	}

	url := "https://gitee.com/openeuler/cve-manager/tree/master/cve-vulner-manager/cve-py/newexcels"
	html, uErr := util.UrlToHTML(url)
	if uErr != nil {
		logs.Error("util.UrlToHTML error: ", uErr, url)
		return "", uErr
	}
	for i := 3; ; i += 2 {
		names, hErr := htmlquery.QueryAll(html, fmt.Sprintf("//div[@id='tree-slider']/div[%d]/div[1]/a/@title", i))
		if hErr != nil {
			logs.Error("htmlquery.QueryAll error:", hErr)
			return "", hErr
		}
		if len(names) == 0 {
			break
		}
		name := htmlquery.SelectAttr(names[0], "title")
		if strings.HasSuffix(name, ".xls") || strings.HasSuffix(name, ".xlsx") {
			downloadUrl := fmt.Sprintf("https://gitee.com/openeuler/cve-manager/raw/master/cve-vulner-manager/cve-py/newexcels/%s", name)
			resp, gErr := http.Get(downloadUrl)
			if gErr != nil {
				logs.Error("GET", url, "error:", gErr.Error())
				continue
			}

			if resp.StatusCode != http.StatusOK {
				logs.Error("get", downloadUrl, resp.Status)
				_ = resp.Body.Close()
				continue
			}
			saveFile, cErr := os.Create(filePath + name)
			if cErr != nil {
				logs.Error("create file error:", cErr)
				_ = resp.Body.Close()
				continue
			}
			_, cErr = io.Copy(saveFile, resp.Body)
			if cErr != nil {
				logs.Error("copy file error:", cErr)
				_ = resp.Body.Close()
				_ = saveFile.Close()
				continue
			}
			_ = resp.Body.Close()
			_ = saveFile.Close()
		} else {
			logs.Warn("not Excel file")
		}
	}
	return filePath, nil
}

func HandleTwo() (string, error) {
	filePath := beego.AppConfig.String("timedtask::packageDir") + "mappingexcels/"
	fErr := util.MakeDir(filePath)
	if fErr != nil {
		logs.Error("util.makeDir error: ", fErr)
		return "", fErr
	}

	url := "https://gitee.com/openeuler/cve-manager/tree/master/cve-vulner-manager/cve-py/mappingexcels"
	html, hErr := util.UrlToHTML(url)
	if hErr != nil {
		return "", hErr
	}
	for i := 3; ; i += 2 {
		names, qErr := htmlquery.QueryAll(html, fmt.Sprintf("//div[@id='tree-slider']/div[%d]/div[1]/a/@title", i))
		if qErr != nil {
			logs.Error("xpath match error:", qErr)
			return "", qErr
		}
		if len(names) == 0 {
			break
		}
		name := htmlquery.SelectAttr(names[0], "title")
		if strings.HasSuffix(name, ".xls") || strings.HasSuffix(name, ".xlsx") {
			downloadUrl := fmt.Sprintf("https://gitee.com/openeuler/cve-manager/raw/master/cve-vulner-manager/cve-py/mappingexcels/%s", name)
			resp, gErr := http.Get(downloadUrl)
			if gErr != nil {
				logs.Error("GET", url, "error:", gErr.Error())
				continue
			}

			if resp.StatusCode != http.StatusOK {
				logs.Error("get", downloadUrl, resp.Status)
				_ = resp.Body.Close()
				continue
			}
			saveFile, cErr := os.Create(filePath + name)
			if cErr != nil {
				logs.Error("create file error:", cErr)
				_ = resp.Body.Close()
				continue
			}
			_, cErr = io.Copy(saveFile, resp.Body)
			if cErr != nil {
				logs.Error("copy file error:", cErr)
				_ = resp.Body.Close()
				_ = saveFile.Close()
				continue
			}
			_ = resp.Body.Close()
			_ = saveFile.Close()
		} else {
			logs.Warn("not Excel file")
		}
	}
	return filePath, nil
}

func HandleThree() (string, error) {
	filePath := beego.AppConfig.String("timedtask::packageDir") + "import_excels/"
	fErr := util.MakeDir(filePath)
	if fErr != nil {
		logs.Error("util.makeDir error: ", fErr)
		return "", fErr
	}

	url := "https://gitee.com/openeuler/cve-manager/tree/master/cve-vulner-manager/cve-py/import_excels"

	html, uErr := util.UrlToHTML(url)
	if uErr != nil {
		return "", uErr
	}

	for i := 3; ; i += 2 {
		names, qErr := htmlquery.QueryAll(html, fmt.Sprintf("//div[@id='tree-slider']/div[%d]/div[1]/a/@title", i))
		if qErr != nil {
			logs.Error("xpath match error:", qErr)
			return "", qErr
		}
		if len(names) == 0 {
			break
		}

		name := htmlquery.SelectAttr(names[0], "title")
		if strings.HasSuffix(name, ".xls") || strings.HasSuffix(name, ".xlsx") {
			downloadUrl := fmt.Sprintf("https://gitee.com/openeuler/cve-manager/raw/master/cve-vulner-manager/cve-py/import_excels/%s", name)
			resp, gErr := http.Get(downloadUrl)
			if gErr != nil {
				logs.Error("GET", url, "error:", gErr.Error())
				_ = resp.Body.Close()
				continue
			}

			if resp.StatusCode != http.StatusOK {
				logs.Error("get", downloadUrl, resp.Status)
				_ = resp.Body.Close()
				continue
			}
			saveFile, cErr := os.Create(filePath + name)
			if cErr != nil {
				logs.Error("create file error:", cErr)
				_ = resp.Body.Close()
				continue
			}
			_, cErr = io.Copy(saveFile, resp.Body)
			if cErr != nil {
				logs.Error("copy file error:", cErr)
				_ = resp.Body.Close()
				_ = saveFile.Close()
				continue
			}
			_ = resp.Body.Close()
			_ = saveFile.Close()
		} else {
			logs.Warn("not Excel file")
		}
	}
	return filePath, nil
}

func HandleFour() (string, error) {
	filePath := beego.AppConfig.String("timedtask::packageDir") + "package_committer_excels/"
	fErr := util.MakeDir(filePath)
	if fErr != nil {
		logs.Error("util.makeDir error: ", fErr)
		return "", fErr
	}

	url := "https://gitee.com/openeuler/cve-manager/tree/master/cve-vulner-manager/cve-py/package_committer_excels"
	html, hErr := util.UrlToHTML(url)
	if hErr != nil {
		return "", hErr
	}

	for i := 3; ; i += 2 {
		names, qErr := htmlquery.QueryAll(html, fmt.Sprintf("//div[@id='tree-slider']/div[%d]/div[1]/a/@title", i))
		if qErr != nil {
			logs.Error("xpath match error:", qErr)
			return "", qErr
		}
		if len(names) == 0 {
			break
		}
		name := htmlquery.SelectAttr(names[0], "title")
		if strings.HasSuffix(name, ".xls") || strings.HasSuffix(name, ".xlsx") {
			downloadUrl := fmt.Sprintf("https://gitee.com/openeuler/cve-manager/raw/master/cve-vulner-manager/cve-py/package_committer_excels/%s", name)
			resp, dErr := http.Get(downloadUrl)
			if dErr != nil {
				logs.Error("GET", url, "error:", dErr.Error())
				_ = resp.Body.Close()
				continue
			}

			if resp.StatusCode != http.StatusOK {
				logs.Error("get", downloadUrl, resp.Status)
				_ = resp.Body.Close()
				continue
			}

			saveFile, cErr := os.Create(filePath + name)
			if cErr != nil {
				logs.Error("create file error:", cErr)
				_ = resp.Body.Close()
				continue
			}
			_, cErr = io.Copy(saveFile, resp.Body)
			if cErr != nil {
				logs.Error("copy file error:", cErr)
				_ = resp.Body.Close()
				_ = saveFile.Close()
				continue
			}
			_ = resp.Body.Close()
			_ = saveFile.Close()
		} else {
			logs.Warn("not Excel file")
		}
	}
	return filePath, nil
}

// DownloadSpecErrorExcels download spec_error_excels
func DownloadSpecErrorExcels() (string, error) {
	filePath := beego.AppConfig.String("timedtask::packageDir") + "spec_error_excels/"
	fErr := util.MakeDir(filePath)
	if fErr != nil {
		logs.Error("util.makeDir error: ", fErr)
		return "", fErr
	}

	url := "https://gitee.com/openeuler/cve-manager/tree/master/cve-vulner-manager/cve-py/spec_error_excels"
	html, uErr := util.UrlToHTML(url)
	if uErr != nil {
		return "", uErr
	}

	for i := 3; ; i += 2 {
		names, qErr := htmlquery.QueryAll(html, fmt.Sprintf("//div[@id='tree-slider']/div[%d]/div[1]/a/@title", i))
		if qErr != nil {
			logs.Error("htmlquery.QueryAll, qErr: ", qErr)
			return "", qErr
		}
		if len(names) == 0 {
			break
		}
		name := htmlquery.SelectAttr(names[0], "title")
		if strings.HasSuffix(name, ".xls") || strings.HasSuffix(name, ".xlsx") {
			downloadUrl := fmt.Sprintf("https://gitee.com/openeuler/cve-manager/raw/master/cve-vulner-manager/cve-py/spec_error_excels/%s", name)
			resp, dErr := http.Get(downloadUrl)
			if dErr != nil {
				logs.Error("GET", url, "error:", dErr.Error())
				continue
			}

			if resp.StatusCode != http.StatusOK {
				logs.Error("get", downloadUrl, resp.Status)
				_ = resp.Body.Close()
				continue
			}

			saveFile, cErr := os.Create(filePath + name)
			if cErr != nil {
				logs.Error("create file error:", cErr)
				_ = resp.Body.Close()
				continue
			}
			_, cErr = io.Copy(saveFile, resp.Body)
			if cErr != nil {
				logs.Error("copy file error:", cErr)
				_ = resp.Body.Close()
				_ = saveFile.Close()
				continue
			}
			_ = resp.Body.Close()
			_ = saveFile.Close()
		} else {
			logs.Warn("not Excel file")
		}
	}
	return filePath, nil
}
